//
//  UIButton+Extension.swift
//  Test
//
//  Created by ZWJY on 2021/8/20.
//

import Foundation
import UIKit

// MARK: - 快速创建Button
public extension UIButton {

    /// 快速创建文本按钮
    convenience init(title: String? = nil, titleColor: UIColor? = nil, selectTitle: String? = nil, selectTitleColor: UIColor? = nil, font: UIFont) {
        self.init()
        self.setTitle(title, for: .normal)
        self.setTitleColor(titleColor, for: .normal)
        self.setTitle(selectTitle, for: .selected)
        self.setTitleColor(selectTitleColor, for: .selected)
        self.titleLabel?.font = font
        self.adjustsImageWhenHighlighted = false
    }

    /// 快速创建图片按钮
    convenience init(image: UIImage? = nil, selectImage: UIImage? = nil) {
        self.init()
        self.setImage(image, for: .normal)
        self.setImage(selectImage, for: .selected)
        self.adjustsImageWhenHighlighted = false
    }

    /// 快速创建图片、文字按钮
    convenience init(title: String? = nil, image: UIImage? = nil, titleColor: UIColor? = nil, font: UIFont) {
        self.init()
        self.setTitle(title, for: .normal)
        self.setImage(image, for: .normal)
        self.setTitleColor(titleColor, for: .normal)
        self.titleLabel?.font = font
        self.adjustsImageWhenHighlighted = false
    }

    func pg_sizeToFit() -> Self {
        self.sizeToFit()
        return self
    }

    func pg_font(_ font: UIFont) -> Self {
        self.titleLabel?.font = font
        return self
    }
    
    func pg_isEnabled(_ isEnabled: Bool) -> Self {
        self.isEnabled = isEnabled
        return self
    }

    func pg_isSelected(_ select: Bool) -> Self {
        self.isSelected = select
        return self
    }
    
    func pg_setTitle(_ title: String?, _ state: UIControl.State) -> Self {
        self.setTitle(title, for: state)
        return self
    }
    
    func pg_setTitleColor(_ color: UIColor?, _ state: UIControl.State) -> Self {
        self.setTitleColor(color, for: state)
        return self
    }
    
    func pg_setImage(_ image: UIImage?, _ state: UIControl.State) -> Self {
        self.setImage(image, for: state)
        return self
    }
    
    func pg_setBackgroundImage(_ image: UIImage?, _ state: UIControl.State) -> Self {
        self.setBackgroundImage(image, for: state)
        return self
    }
    
    func pg_contentHorizontalAlignment(_ alignment: ContentHorizontalAlignment) -> Self {
        self.contentHorizontalAlignment = alignment
        return self
    }
    
    func pg_contentVerticalAlignment(_ alignment: ContentVerticalAlignment) -> Self {
        self.contentVerticalAlignment = alignment
        return self
    }
    
    func pg_addTarget(_ target: Any?, _ action: Selector) -> Self {
        self.addTarget(target, action: action, for: .touchUpInside)
        return self
    }
    
    func pg_adjustsImageWhenHighlighted(_ highlighted: Bool) -> Self {
        self.adjustsImageWhenHighlighted = highlighted
        return self
    }
}

// MARK: - 图片文字位置调整 (需要先确定UIButton大小， layoutSubviews、或者     self.layoutIfNeeded() self.setNeedsLayout())
extension UIButton {
    enum ButtonImageStyle {
        case top /// image在上，label在下
        case left /// image在左，label在右
        case bottom /// image在下，label在上
        case right /// image在右，label在左
    }

    func layoutButtonImage(style:ButtonImageStyle=ButtonImageStyle.left,space:CGFloat = 5){

        let imageWith = self.imageView?.bounds.width ?? 0
        let imageHeight = self.imageView?.bounds.height ?? 0

        let labelWidth = self.titleLabel?.intrinsicContentSize.width ?? 0
        let labelHeight = self.titleLabel?.intrinsicContentSize.height ?? 0

        var imageEdgeInsets = UIEdgeInsets.zero
        var labelEdgeInsets = UIEdgeInsets.zero
        var contentEdgeInsets = UIEdgeInsets.zero

        let bWidth = self.bounds.width

        let min_height = min(imageHeight, labelHeight)

        switch style {
        case .left:
            self.contentVerticalAlignment = .center
            imageEdgeInsets = UIEdgeInsets(top: 0,
                                           left: 0,
                                           bottom: 0,
                                           right: 0)
            labelEdgeInsets = UIEdgeInsets(top: 0,
                                           left: space,
                                           bottom: 0,
                                           right: -space)
            contentEdgeInsets = UIEdgeInsets(top: 0,left: 0,bottom: 0,right: space)
        case .right:
            self.contentVerticalAlignment = .center
            var w_di = labelWidth + space/2
            if (labelWidth+imageWith+space) > bWidth{
                let labelWidth_f = self.titleLabel?.frame.width ?? 0
                w_di = labelWidth_f + space/2
            }
            imageEdgeInsets = UIEdgeInsets(top: 0,
                                           left: w_di,
                                           bottom: 0,
                                           right: -w_di)
            labelEdgeInsets = UIEdgeInsets(top: 0,
                                           left: -(imageWith+space/2),
                                           bottom: 0,
                                           right: imageWith+space/2)
            contentEdgeInsets = UIEdgeInsets(top: 0, left: space/2, bottom: 0, right: space/2.0)
        case .top:
            //img在上或者在下 一版按钮是水平垂直居中的
            self.contentHorizontalAlignment = .center
            self.contentVerticalAlignment = .center

            var w_di = labelWidth/2.0
            //如果内容宽度大于button宽度 改变计算方式
            if (labelWidth+imageWith+space) > bWidth{
                w_di = (bWidth - imageWith)/2
            }
            //考虑图片+显示文字宽度大于按钮总宽度的情况
            let labelWidth_f = self.titleLabel?.frame.width ?? 0
            if (imageWith+labelWidth_f+space)>bWidth{
                w_di = (bWidth - imageWith)/2
            }
            imageEdgeInsets = UIEdgeInsets(top: -(labelHeight+space),
                                           left: w_di,
                                           bottom: 0,
                                           right: -w_di)
            labelEdgeInsets = UIEdgeInsets(top: 0,
                                           left: -imageWith,
                                           bottom:-(space+imageHeight),
                                           right: 0)
            let h_di = (min_height+space)/2.0
            contentEdgeInsets = UIEdgeInsets(top:h_di,left: 0,bottom:h_di,right: 0)
        case .bottom:
            //img在上或者在下 一版按钮是水平垂直居中的
            self.contentHorizontalAlignment = .center
            self.contentVerticalAlignment = .center
            var w_di = labelWidth/2
            //如果内容宽度大于button宽度 改变计算方式
            if (labelWidth+imageWith+space) > bWidth{
                w_di = (bWidth - imageWith)/2
            }
            //考虑图片+显示文字宽度大于按钮总宽度的情况
            let labelWidth_f = self.titleLabel?.frame.width ?? 0
            if (imageWith+labelWidth_f+space)>bWidth{
                w_di = (bWidth - imageWith)/2
            }
            imageEdgeInsets = UIEdgeInsets(top: 0,
                                           left: w_di,
                                           bottom: -(labelHeight+space),
                                           right: -w_di)
            labelEdgeInsets = UIEdgeInsets(top: -(space+imageHeight),
                                           left: -imageWith,
                                           bottom: 0,
                                           right: 0)
            let h_di = (min_height+space)/2.0
            contentEdgeInsets = UIEdgeInsets(top:h_di, left: 0,bottom:h_di,right: 0)
        }
        self.contentEdgeInsets = contentEdgeInsets
        self.titleEdgeInsets = labelEdgeInsets
        self.imageEdgeInsets = imageEdgeInsets
    }
}

// MARK: - 防止重复点击
public extension UIButton {

    typealias ActionBlock = ((UIButton)->Void)

    private struct AssociatedKeys {
        static var ActionBlock = "ActionBlock"
        static var ActionDelay = "ActionDelay"
    }

    private var actionBlock: ActionBlock? {
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.ActionBlock, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }

        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.ActionBlock) as? ActionBlock
        }
    }

    private var actionDelay: TimeInterval {
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.ActionDelay, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }

        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.ActionDelay) as? TimeInterval ?? 0
        }
    }

    func addDelayTarget(delay: TimeInterval = 0, action: @escaping ActionBlock) -> Self {
        addTarget(self, action: #selector(btnDelayClick(_:)), for: .touchUpInside)
        actionDelay = delay
        actionBlock = action
        return self
    }

    @objc private func btnDelayClick(_ sender: UIButton) {
        actionBlock?(sender)
        isEnabled = false
        DispatchQueue.main.asyncAfter(deadline: .now() + actionDelay) {
            self.isEnabled = true
        }
    }
}
 
public class DelayTapGestureRecognizer:UITapGestureRecognizer,UIGestureRecognizerDelegate {
    //想间隔的时长
    var intervalTime: TimeInterval = 1.0
    //用于完成间隔的计时器
    private var eventTimer: Timer?
    
    override init(target: Any?, action: Selector?) {
        super.init(target: target, action: action)
        delegate = self
    }
    
    // 是否响应触摸手势的代理方法
    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if (eventTimer != nil) {
            return false
        }
        
        eventTimer = Timer.scheduledTimerWithTimeInterval(interval: intervalTime, repeats: false) {[weak self] timer in
            self?.deinitTimer()
            print("倒计时结束")
        }
        
        return true
    }
    
     func deinitTimer() {
        eventTimer?.invalidate()
        eventTimer = nil
    }
}
